local DarkStreetBroadcastItem = require("View/DarkStreet/SubItem/DarkStreetBroadcastItem")

---@class UIDarkStreet : UIBase
UIDarkStreet = UIBase.New(PanelResNames.UIDarkStreet)
local t = UIDarkStreet
local m_state = nil
local setTimer = nil

function t.Init(func)
    UIBase.Init(t, func)
end

function t:OnCreate()
    if not UIPackage.GetById("FUI/Emoji") then
        self.isNeedRemovePackage = true;
        AddUIPackageDepend(PanelNames.UIDarkStreet, "FUI/Emoji")
    end
    self.isShowResult = false
    self.broadcastItemList = {}
    self.broadcastItemCacheList = {}
    self.broadcastPos = nil
    self.BackButton = self:GetChild("Btn_BackButton")
    self.btnEmoji = self:GetChild("Btn_Emoji")
    self.Btn_ClickScene = self:GetChild("Btn_ClickScene")
    self.List_Emoji = self:GetList("List_Emoji")
    self.Btn_CloseEmoji = self:GetChild("Btn_CloseEmoji")
    self.ctrlEmoji = self:GetController("Emoji")
    self.Btn_EasyBag = self:GetChild("Btn_EasyBag")
    self.Text_CountDown = self:GetChild("Text_CountDown")
    self.Text_WaitingTips = self:GetChild("Text_WaitingTips")
    self.Btn_info = self:GetChild("Btn_info")
    self.Com_KillMessage = self:GetChild("Com_KillMessage")
    self.ctrlBroadcast = self:GetController("broadcast")
    self.List_BattleReward = self:GetList("List_BattleReward")
    self.List_BoxReward = self:GetList("List_BoxReward")
    self.List_BoxAttr = self:GetList("List_BoxAttr")
    self.Btn_CloseEmoji.visible = false
    self.List_Emoji.visible = false
    self:RegisterOnClick(self.BackButton,self.ClickClose)
    self:RegisterOnClick(self.btnEmoji,self.ClickEmoji)
    self:RegisterTouchBegin(self.Btn_ClickScene,self.ClickScene)
    self:RegisterOnClick(self.Btn_CloseEmoji,self.ClickCloseEmoji)
    self:RegisterOnClick(self.Btn_info,self.ClickInfo)
    self:RegisterOnClick(self.Btn_EasyBag,self.ClickBag)
    self:SetDynamicList(self.List_Emoji,self.EmojiRender)
    self:SetDynamicList(self.List_BattleReward,self.BattleRewardRender)
    self:SetDynamicList(self.List_BoxReward,self.BoxRewardRender)
    self:SetDynamicList(self.List_BoxAttr,self.BoxRefreshRender,self,true)

    self:RegisterEvent(RedRob.Config.Event.ActorCreate,self.PlayerCreate)
    self:RegisterEvent(RedRob.Config.Event.BattleTimeInit,self.BattleTimeInit)
    self:RegisterEvent(RedRob.Config.Event.MineralReward,self.MineralReward)
    self:RegisterEvent(RedRob.Config.Event.BattleTimeOut,self.BattleTimeOut)
    self:RegisterEvent(Config.EventType.DarkStreetRoomStatusChange,self.DarkStreetRoomStatusChange)
    self:RegisterEvent(Config.EventType.DarkStreetResult,self.DarkStreetResult)
    self:RegisterEvent(RedRob.Config.Event.ResourceRefreshTip,self.ResourceRefreshTip)
    self:RegisterEvent(Config.EventType.ResDarkMatchSuc,self.ResDarkMatchSucMsg)
    self:TimeCall(self.Update,1000,-1)
    self.emojiList = logicMgr.ChatManager.LoadEmoji()
    self.List_Emoji.numItems = #self.emojiList
    self.List_BoxAttr.numItems = 0
    self.ctrlBroadcast.selectedIndex = 1
    self.bagList = {}
    self.resRefreshDataList = {}
    self.broadcastPos = self.Com_KillMessage.xy
    ---@type DarkStreetBroadcastItem
    self.broadcastItem = DarkStreetBroadcastItem.New()
    self.broadcastItem:OnCreate(self.Com_KillMessage,self.BroadCastDone,self)
    --local item = self:InitBroadcastItem(self.Com_KillMessage)
    --self:ReturnBroadcastToPool(item)
    self.isDestroy = false
    self.isBroadcasting = false
    self.isMatchSucSend = false
    self.curOpenStage = 0
end

function t:OnEnable()
    AudioManager.Play(25)
    

    self:Update()
    if setTimer then
        utimer.remove(setTimer)
        setTimer = nil
    end
    setTimer = utimer.frameCall(function()
        if Time.timeScale > 1 then
            Time.timeScale = 1
        end
    end,-1)
end
function t:OnDisable()
end
function t:OnDestroy()
    self.broadcastItemList = nil
    self.broadcastItemCacheList = nil
    self.emojiList = nil
    self.bagList = nil
    self.isDestroy = true
    self.resRefreshDataList = nil

    if self.isNeedRemovePackage and UIPackage.GetById("FUI/Emoji") then
        UIPackage.RemovePackage("FUI/Emoji")
    end
    if setTimer then
        utimer.remove(setTimer)
        setTimer = nil
    end
    --if self.curOpenStage ~= RedRob.Config.OpenStage.open then
    --    DarkStreetHandler.ReqDarkApply(false)
    --end
end
function t:Update()
    self:UpdateBroadcast()
    self:UpdateCountDownTime()
    self:UpdateBoxRefreshTip()
end
function t:UpdateWaitingTips()


end
function t:UpdateCountDownTime()
    local bat = RedRob.ClientBattle
    if bat.closeTime == 0 then
        self.Text_CountDown.text = ""
        return
    end
    local BattleStage = RedRob.Config.BattleStage
    local stage,remainTime = bat.GetBattleStage()
    local count = RedRob.ActorManager.GetPlayerCount()
    local waitCount = dataTable.getGlobalInt(352)
    local maxCount = dataTable.getGlobalInt(342)
    self.curOpenStage = stage
    --local wait = bat.GetWaitingTime() - bat.GetBattleTime()
    if stage == BattleStage.waiting then
        local str = getLanguage("DarkLaneTipes_2")--等待其他玩家%d/%d
        if count >= waitCount then
            self.Text_WaitingTips.text = string.format(str,string.TextColor(count,"#CBFFAB"),maxCount)
            self.Text_CountDown.text = string.format(getLanguage("DarkLaneTipes_4"),HelperFunc.GetMinuteSecond(remainTime))--距离战斗开始还有%s
        else
            self.Text_WaitingTips.text = string.format(str,count,maxCount)
            self.Text_CountDown.text = string.format(getLanguage("DarkLaneTipes_29"),HelperFunc.GetMinuteSecond(remainTime))--等待玩家进入
        end
        --self.Text_CountDown.text = string.format(getLanguage("DarkStreetTimeTips1"),HelperFunc.GetMinuteSecond(remainTime))
        --logicMgr.DarkStreetMgr.isMatchSuc = false
        t:RefreshState(1)
    elseif stage == BattleStage.battle then
        self.Text_CountDown.text = string.format(getLanguage("DarkLaneTipes_5"),HelperFunc.GetMinuteSecond(remainTime))--距离暗巷关闭还有%s
        --self.Text_CountDown.text = string.format(getLanguage("DarkStreetTimeTips2"),HelperFunc.GetMinuteSecond(remainTime))
        self.Text_WaitingTips.text = string.format(getLanguage("DarkLaneTipes_3"),count,maxCount) --玩家人数%d/%d
        t:RefreshState(2)
        --if logicMgr.DarkStreetMgr.isMatchSuc then
        --    self:ResDarkMatchSucMsg()
        --end
    else
        --logicMgr.DarkStreetMgr.isMatchSuc = false
        --self.Text_WaitingTips.text = string.format(getLanguage("DarkLaneTipes_3"),count,maxCount) --玩家人数%d/%d
        --self.Text_CountDown.text = string.format(getLanguage("DarkLaneTipes_44"))
    end
end

--1.站街等待 2.比赛中 3.结束
function t:RefreshState(state)
    if state == m_state then
        return
    end
    if state == 1 then
        AudioManager.Play(26)
    elseif state == 2 and not t.isShowResult then
        AudioManager.Play(27)
    elseif state == 3 then
        AudioManager.Play(28)
    end
    m_state = state
end
--[[function t:InitBroadcastItem(go)
    local winText = go:GetChild("Text_PlayerName1")
    local failedText = go:GetChild("Text_PlayerName2")
    local numText = go:GetChild("Text_RewardNum")
    local transition = go:GetTransition("Effect_Kill")
    local head1 = go:GetChild("Btn_Head01")
    local icon1 = head1:GetChild("head"):GetChild("HeadIcon")
    local frame1 = head1:GetChild("frame")
    local head2 = go:GetChild("Btn_Head02")
    local icon2 = head2:GetChild("head"):GetChild("HeadIcon")
    local frame2 = head1:GetChild("frame")
    local ctrlKill = go:GetController("Kill")
    local ctrlType = go:GetController("Type")
    local singleHead = go:GetChild("Btn_HeadSingle")
    local singleIcon = singleHead:GetChild("head"):GetChild("HeadIcon")
    local singleFrame = singleHead:GetChild("frame")
    local singleName = go:GetChild("Text_PlayerNameSingle")
    self.fguiObj:AddChild(go)
    local item = {go = go,winText = winText,failedText = failedText,numText = numText,anim = transition,
                  icon1 = icon1,frame1 = frame1,icon2 = icon2,frame2 = frame2,ctrlKill = ctrlKill,
                  ctrlType = ctrlType,singleIcon = singleIcon,singleFrame = singleFrame,singleName = singleName}
    table.insert(self.broadcastItemList,item)
    return item
end]]
function t:UpdateBroadcast()
    if self.isBroadcasting then
        return
    end
    local tb = logicMgr.DarkStreetMgr.GetBroadcastMsg()
    if not tb then return end
    
    self.isBroadcasting = true
    self.broadcastItem:Set(tb,self.broadcastPos.x,self.broadcastPos.y)
    --[[local winPlayer = RedRob.ActorManager.GetActor(tb.winId)
    local failedPlayer = RedRob.ActorManager.GetActor(tb.failedId)
    if not winPlayer or not failedPlayer then return end
    local item = self:GetBroadcastItem()
    item.winText.text = winPlayer:GetName()
    item.failedText.text = failedPlayer:GetName()
    item.numText.text = tostring(tb.count)
    item.go:SetXY(self.broadcastPos.x,self.broadcastPos.y)
    local winData = RedRob.GameMode.GetPlayerData(tb.winId)
    local failData = RedRob.GameMode.GetPlayerData(tb.failedId)
    if failData.winStreakCount >= 3 then
        --终结
        item.ctrlKill.selectedIndex = 5
        item.ctrlType.selectedIndex = 1
    end
    UIComponentInterface:SetPlayerIcon(item.icon1,winPlayer:GetModelId(),item.frame1,winPlayer:GetPicFrame())
    UIComponentInterface:SetPlayerIcon(item.icon2,failedPlayer:GetModelId(),item.frame2,failedPlayer:GetPicFrame())
    item.anim:Play(function()
        self:ReturnBroadcastToPool(item)
    end)]]
end
---@param item DarkStreetBroadcastItem
function t:BroadCastDone(item)
    
    self.isBroadcasting = false
    self:UpdateBroadcast()
end
--[[function t:GetBroadcastItem()
    local item
    if #self.broadcastItemCacheList > 0 then
        item = table.remove(self.broadcastItemCacheList)
    else
        local go = newGComponent("Com_KillMessage","UIDarkStreet")
        item = self:InitBroadcastItem(go)
    end
    item.go.visible = true
    return item
end
function t:ReturnBroadcastToPool(item)
    if not item.go then return end
    item.go.visible = false
    table.insert(self.broadcastItemCacheList,item)
    for k,v in pairs(self.broadcastItemList) do
        table.remove(self.broadcastItemList,k)
        break
    end
end]]
function t:EmojiRender(index,obj)
    local name = self.emojiList[index]
    obj.icon = "ui://Emoji/" .. name
    obj.onClick:Clear()
    obj.onClick:Add(function()
        RedRob.BattleMsgHandler.ReqEmoji(name)
        self.ctrlEmoji.selectedIndex = 0;
        self.Btn_CloseEmoji.visible = false
    end)
end
--战斗获得
function t:BattleRewardRender(index,obj)
    local ctrl = CtrlManager.GetCtrl(PanelNames.Item)
    local data = RedRob.GameMode.GetMyRes()
    if data then
        ctrl.initData(obj,{itemModelId = logicMgr.DarkStreetMgr.resItemModelId,num = data.resNum })
    else
        ctrl.initData(obj,{itemModelId = logicMgr.DarkStreetMgr.resItemModelId,num = 0 })
    end
    --ctrl.DisableClick(obj)
end
--夺宝获得
function t:BoxRewardRender(index,obj)
    local data = self.bagList[index]
    local ctrl = CtrlManager.GetCtrl(PanelNames.Item)
    ctrl.initData(obj,data)
end
function t:ClickClose()
    logicMgr.DarkStreetMgr.Track_clickExit()
    --退出将自动进入托管状态，确认要退出吗
    logicMgr.UIShowManager.ShowCommonConfirm(getLanguage("DarkLaneTipes_6"),nil,function()
        RedRob.ClientBattle.Leave()
        logicMgr.DarkStreetMgr.Track_exitSuccess(1, 0)
    end)

end
function t:ClickEmoji()
    self.Btn_CloseEmoji.visible = true
    self.List_Emoji.visible = true
    self.ctrlEmoji.selectedIndex = 1
end
function t:ClickInfo()
    logicMgr.UIShowManager.ShowCommonTips("DarkLaneTipes_16","DarkLaneTipes_17")
end
function t:ClickScene()
    RedRob.KeyController.Touched()
end
function t:ClickCloseEmoji()
    self.Btn_CloseEmoji.visible = false
    self.List_Emoji.visible = false
end
---@param player RedRob.Player
function t:PlayerCreate(player)
    self:UpdateCountDownTime()
end
function t:BattleTimeInit()
    --self:UpdateCountDownTime()
    local bat = RedRob.ClientBattle
    if not bat.IsBattleWaiting() and not bat.IsFightStart() then
        showUI(PanelNames.UIDarkStreetCountDown)
    end
end
function t:DarkStreetRoomStatusChange(status)
    if status == 0 then--房间失效 人数不齐，房间将销毁
        self.isShowResult = true
        t:RefreshState(3)
        loginHandler.R_LeaveUnionWar()
        logicMgr.UIShowManager.ShowCommonConfirm(getLanguage("DarkLaneTipes_7"),nil,function()
            RedRob.ClientBattle.Leave()
        end,function()
            RedRob.ClientBattle.Leave()
        end)
    end
end
function t:DarkStreetResult()
    if self.isShowResult then return end
    self.isShowResult = true
    t:RefreshState(3)
    loginHandler.R_LeaveUnionWar()
    closeUI(PanelNames.UIDarkStreetDead)
    showUI(PanelNames.UIDarkStreetReward)
    self:RemoveTimeCall(self.DarkStreetResult)
    self:RemoveTimeCall(self.ClientFinished)
    UISpeed()
end
function t:BattleTimeOut()
    self:TimeCall(self.ClientFinished,2000)
    --[[if self.isShowResult then return end
    local data = RedRob.GameMode.GetPlayerData(RedRob.KeyController.GetCtrlId())
    if data then
        logicMgr.DarkStreetMgr.SetResult(0,data.resNum,0)
    end
    self:TimeCall(self.DarkStreetResult,5000)]]
end
function t:ClientFinished()
    if self.isShowResult then
        return
    end
    loginHandler.R_LeaveUnionWar()
    t:RefreshState(3)
    RedRob.ClientBattle.Leave()
end
function t:ClickBag()
    self.List_BattleReward.numItems = 1
    table.clear(self.bagList)
    for k,v in pairs(RedRob.GameMode.GetBagList()) do
        table.insert(self.bagList,{itemModelId = k,num = v.num})
    end
    if #self.bagList == 0 then
        table.insert(self.bagList,{itemModelId = logicMgr.DarkStreetMgr.resItemModelId,num = 0})
    end
    self.List_BoxReward.numItems = #self.bagList
end
function t:UpdateBoxRefreshTip()
    local needUpdate = false
    local curTime = RedRob.ClientBattle.GetBattleTime()
    for k,v in pairs(self.resRefreshDataList) do
        local time = v.endTime - curTime
        if time > 0 then
            v.ctrlRefresh.selectedIndex = 0
            v.Text_NoRefresh.text = string.format(getLanguage("T_MineralBoxTime"..v.boxType),math.floor(time))
        else
            local cfg = dataTable.getDataTableByStringId("t_mineral",v.id)
            if cfg then
                v.Text_Refresh.text = string.format(getLanguage("DarkLaneTipes_22"),getLanguage(cfg.f_BoxName))
            else
                logError("找不到t_mineral "..v.id)
            end
            v.ctrlRefresh.selectedIndex = 1
            if curTime > v.dieTime then --超出展示时间
                needUpdate = true
            end
        end
    end
    if needUpdate then
        self:ResourceRefreshTip()
    end
end
function t:ResourceRefreshTip()
    table.clear(self.resRefreshDataList)
    local curTime = RedRob.ClientBattle.GetBattleTime()
    for k,v in pairs(RedRob.GameMode.resRefreshTipList) do
        if curTime < v.dieTime then
            for k2,v2 in pairs(v.idList) do
                table.insert(self.resRefreshDataList,{id = v2,endTime = v.endTime,dieTime = v.dieTime})
            end
        end
    end
    self.List_BoxAttr.numItems = #self.resRefreshDataList
    self:UpdateBoxRefreshTip()
end
function t:ResDarkMatchSucMsg()
    if self.isMatchSucSend then return end
    self.isMatchSucSend = true
    DarkStreetHandler.ReqDarkEntry()
end
function t:BoxRefreshRender(index,go)
    local ctrlBox = go:GetController("Box")
    local Text_NoRefresh = go:GetChild("Text_NoRefresh")
    local ctrlRefresh = go:GetController("Type")
    local Text_Refresh = go:GetChild("Text_Refresh")
    local data = self.resRefreshDataList[index]
    local cfg = dataTable.getDataTableByStringId("t_mineral",data.id)
    if not cfg then
        logError("找不到t_mineral "..data.id)
        return
    end
    ctrlBox.selectedIndex = cfg.f_BoxType - 1
    data.boxType = cfg.f_BoxType
    data.Text_NoRefresh = Text_NoRefresh
    data.ctrlRefresh = ctrlRefresh
    data.Text_Refresh = Text_Refresh
end
---@param actor RedRob.Minerals
function t:MineralReward(actor,playerId)
    if actor:GetMineralType() == RedRob.Config.MineralType.box then
        if playerId ~= RedRob.ClientBattle.ctrlActorId then
            return
        end
        local p = actor:GetPos()
        local x,y = RedRob.ClientBattle.WorldToScreenPoint(RedRob.ClientBattle.LocalToWorld(p.x,p.y,p.z))
        x,y = FGUIScreenToLocal(self.fguiObj,x,y)
        local item = newGComponent("Btn_BoxPos","UIDarkStreet")
        x = x - item.width/2
        y = y - item.height/2
        local ctrlShow = item:GetController("BoxReward")
        local reward = item:GetChild("Btn_BoxReward")
        local ctr = logicMgr.CtrlManager.GetCtrl(PanelNames.Item)
        local bagData = RedRob.GameMode.GetBagChangeData()
        if bagData then
            ctr.initData(reward,{itemModelId = bagData.itemModelId,num = bagData.change})
        end
        ctrlShow.selectedIndex = 1
        item:SetXY(x,y)
        self.fguiObj:AddChild(item)
        utimer.delayCall(function()
            if self.isDestroy then
                item:Dispose()
                return
            end
            logicMgr.ItemFlyMgr.FlyByBezier2(item,Vector3(x,y),self.Btn_EasyBag.xy,0,1,function()
                if self.isDestroy then
                    return
                end
                item:Dispose()
            end)
        end,500)
    end
end

return t